package DesignModeTest;

/**
 * 责任链模式
 */
public class TestChain {

  public static void main(String[] args) {
    AbstractLogger abstractLogger = getChainOfLoggers();

    abstractLogger.logMessage(AbstractLogger.debug, "this is an debug message");
    abstractLogger.logMessage(AbstractLogger.error, "this is an error message");
    abstractLogger.logMessage(AbstractLogger.info, "this is an info message");
  }

  private static AbstractLogger getChainOfLoggers() {
    AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.info);
    AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.error);
    AbstractLogger fileLogger = new FileLogger(AbstractLogger.debug);

    errorLogger.setNextLogger(fileLogger);
    fileLogger.setNextLogger(consoleLogger);

    return errorLogger;
  }

}

abstract class AbstractLogger{
  public static int info = 1;
  public static int debug = 2;
  public static int error = 3;

  protected int level;

  protected AbstractLogger nextLogger;

  public void setNextLogger(AbstractLogger nextLogger) {
    this.nextLogger = nextLogger;
  }

  public void logMessage(int level, String message){
    if(this.level <= level) {
      write(message);
    }else if(nextLogger != null) {
      nextLogger.logMessage(level, message);
    }
  }

  abstract protected void write(String message);
}

class ConsoleLogger extends AbstractLogger{

  public ConsoleLogger(int level){
    this.level = level;
  }

  @Override
  protected void write(String message) {
    System.out.println("Console log===" + message);
  }
}

class ErrorLogger extends AbstractLogger {

  public ErrorLogger(int level){
    this.level = level;
  }

  @Override
  protected void write(String message) {
    System.out.println("Error log===" + message);
  }
}

class FileLogger extends AbstractLogger{

  public FileLogger(int level){
    this.level = level;
  }

  @Override
  protected void write(String message) {
    System.out.println("File log===" + message);
  }
}